#include "StdAfx.h"
#include "AdbCmd.h"
#include "log.h"


CAdbCmd::CAdbCmd(void)
{
}


CAdbCmd::~CAdbCmd(void)
{
}

string CAdbCmd::SendAdbCmd(string cmd)
{
	SECURITY_ATTRIBUTES sat;
	STARTUPINFO startupinfo;
	PROCESS_INFORMATION pinfo;
	BYTE buffer[1024];
	DWORD byteRead;

	sat.nLength=sizeof(SECURITY_ATTRIBUTES);
	sat.bInheritHandle=true;
	sat.lpSecurityDescriptor=NULL;
	if(!CreatePipe(&hReadPipe,&hWritePipe,&sat,NULL))
	{
		//MessageBox(NULL, "Create Pipe Error! ", "error! ",MB_OK);
		return "NULL";
	}
	if(!CreatePipe(&hReadPipe2,&hWritePipe2,&sat,NULL))
	{
		//MessageBox(NULL, "Create Pipe2 Error! ", "error! ",MB_OK);
		return "NULL";
	}
	startupinfo.cb=sizeof(STARTUPINFO);
	GetStartupInfo(&startupinfo);
	startupinfo.hStdError=hWritePipe;
	startupinfo.hStdOutput=hWritePipe;
	startupinfo.hStdInput=hReadPipe2;
	startupinfo.dwFlags=STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
	startupinfo.wShowWindow=SW_HIDE;
	TRACE("adb test CreateProcess to exe cmd...\n");

	CString cmdString =CString(cmd.c_str());
	TCHAR* szMsg = new TCHAR[100];
	szMsg = cmdString.GetBuffer(cmdString.GetLength());
	cmdString.ReleaseBuffer();

	log_printf("[TOMTOM_FT] SendAdbCmd cmd = %s \n", szMsg);

	if(!CreateProcess(NULL, szMsg, NULL, NULL, TRUE, NULL, NULL, NULL,&startupinfo,&pinfo))
	{
		DWORD dwError = GetLastError();
		//MessageBox(NULL, "create process error! ", "Error! ",MB_OK);
		return "NULL";
	}

	CloseHandle(hWritePipe);
	CloseHandle(hReadPipe2);
	CloseHandle(pinfo.hThread);
	CloseHandle(pinfo.hProcess);

	TRACE("adb test CreateProcess to exe cmd  over...\n");

	string result="";
	while(true)
	{
		RtlZeroMemory(buffer,1024);
		if(ReadFile(hReadPipe,buffer,1023,&byteRead,NULL)==NULL)
		{
			break;
		}
		//TRACE("adb test CreateProcess to exe cmd  over...result=%s  \n",buffer);
		CString mm(buffer);
		string comInfo(CT2A(mm.GetString()));
		result = result+comInfo;
	}
	CloseHandle(hReadPipe);
	CloseHandle(hWritePipe2);

	return result;
}